package com.lecture.java8.test;

import java.util.ArrayList;
import java.util.List;

public class StringSplitterFSM {
    public static void main(String[] args) {
        String input = "I'm a 10 years old boy, 'And i sleep at 10 pm,and' i eat 10.10 kg food everyday";
        List<String> words = splitString(input);

        for (String word : words) {
            System.out.print("'" + word + "'，");
        }
    }

    public static List<String> splitString(String input) {
        List<String> words = new ArrayList<>();
        StringBuilder currentWord = new StringBuilder();

        // 定义有限状态机的状态
        //enum State { OUTSIDE_WORD, INSIDE_WORD, INSIDE_TIME }
        State currentState = State.OUTSIDE_WORD;

        // 遍历输入字符串
        for (char c : input.toCharArray()) {
            //Whitespace 空格
            //letterOrDigit 字母或者数字
            if (Character.isWhitespace(c) || !Character.isLetterOrDigit(c)) {
                if (currentState == State.INSIDE_WORD && c != '\'') {
                    // 如果在单词内部遇到空白字符或非字母/数字字符，则将当前单词添加到列表中
                    words.add(currentWord.toString());
                    currentWord.setLength(0); // 重置当前单词
                } else if (currentState == State.INSIDE_TIME && !Character.isDigit(c) && c != ':' && c != '.') {
                    // 如果在时间内部遇到非数字、非冒号和非小数点字符，则将当前时间添加到列表中
                    words.add(currentWord.toString());
                    currentWord.setLength(0); // 重置当前时间
                } else {
                    currentWord.append(c);
                }
                currentState = State.OUTSIDE_WORD;
            } else {
                // 如果是字母或数字字符，则将字符添加到当前单词或时间
                if (Character.isDigit(c) || c == ':' || c == '.') {
                    currentState = State.INSIDE_TIME;
                } else {
                    currentState = State.INSIDE_WORD;
                }
                currentWord.append(c);
            }
        }

        // 处理最后一个单词或时间
        if (currentState == State.INSIDE_WORD || currentState == State.INSIDE_TIME) {
            words.add(currentWord.toString());
        }

        return words;
    }
}
